package com.clps.algorithm.chapter05.变位词组;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * 给定一组单词,请将他们按照位次分组,例如输入一组单词["eat", "tea", "tan", "ate", "nat", "bat"]，则可以分成三组，分别是["eat", "tea", "ate"]、["tan", "nat"]和["bat"]。假设单词中只包含小写的英文字母。
 */
public class demo01 {
    public static void main(String[] args) {

    }

    public List<List<String>> groupAnaGrams(String[] strs){
        int hash[] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,
                43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101};

        Map<Long, List<String>> groups = new HashMap<>();
        for (String str : strs) {
            long wordhash = 1;
            for (int i = 0; i <str.length() ; i++) {
                wordhash *=hash[str.charAt(i)-'a'];
            }

            groups.putIfAbsent(wordhash,new LinkedList<String>());
            groups.get(wordhash).add(str);
        }

        return  new LinkedList<>(groups.values());
    }
}
